# !/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
from PyQt6.QtCore import pyqtSignal
from PyQt6.QtWidgets import QDialog
from view.tree import Ui_tree
from service.tishi_service import Tishi

# ==============================================================================
# view 8.模块信息
# ==============================================================================


class Tree(QDialog, Ui_tree):
    """模块信息页面"""
    confirmed_signal_tree = pyqtSignal()

    def __init__(self, case_db, modulename=None, moduleid=None, flag=None, parent=None):
        super().__init__(parent)
        self.parent_name = None
        self.setupUi(self)  # 直接调用self的setupUi方法
        self.modulename = modulename  # 选择模块名称
        self.moduleid = moduleid  # 编号，0:新增根
        self.flag = flag  # 1 编辑，0 新增
        self.case_db = case_db
        self.case_db.connect()
        self.ts = Tishi()

        self.quxiao.setAutoDefault(False)  # 取消回车激活按钮
        self.baocun.setAutoDefault(False)

    def mkedit(self):
        """打开编辑、新增页面，反显模块信息"""
        if self.flag == 1:  # 编辑
            parent_id = self.case_db.query_one(f"select parent_id,remark from module where moduleid = '{self.moduleid}'")
            if parent_id[0] == 0:  # 查询父节点
                self.parent_name = "根节点"
                self.fujiedian.addItem(self.parent_name)
            else:
                parent_name = self.case_db.query_one(
                    f"select modulename,moduleid from module where moduleid = '{parent_id[0]}'")
                self.parent_name = parent_name[0]
                self.fujiedian.addItem(parent_name[0] + '—ID:' + str(parent_name[1]))  # 设置下拉框
            self.name.setText(self.modulename)
            self.textEdit.setText(parent_id[1])

        elif self.moduleid == 0:  # 新增根
            self.fujiedian.addItem("根节点")

        elif self.flag == 0:  # 新增
            level = self.case_db.query_one(f"select level from module where moduleid = '{self.moduleid}'")
            if level[0] == 2:
                self.ts.xinxi("系统只支持三级目录，请选择一级、二级节点新增模块！")
            else:
                self.fujiedian.addItem(self.modulename + '—ID:' + str(self.moduleid))
        logging.info('反显模块信息')

    def mkcx(self):
        """模糊查询模块名称，只能查询根、1级模块"""
        value = ['%' + self.chaxun.text() + '%']
        row = self.case_db.query_many(
            f'''select modulename,moduleid from module where modulename like ? and status = 10 and level != 2 
                    and moduleid != {self.moduleid}''', value)
        row.reverse()
        self.fujiedian.clear()  # 清空下拉框
        for parent_name in row:
            self.fujiedian.addItem(parent_name[0] + '—ID:' + str(parent_name[1]))
        self.fujiedian.addItem("根节点")
        logging.info('模糊查询模块名称，查询根、1级模块')

    def mksave(self):
        """编辑新增，模块"""
        name = self.name.text()  # 获取各输入框文本
        self.baocun.setEnabled(False)  # 保存按钮置灰
        remark = self.textEdit.toPlainText()       # 说明
        if not name:
            self.ts.xinxi("模块名称不能为空！")
            self.baocun.setEnabled(True)  # 保存按钮
            return

        parts = self.fujiedian.currentText().split("—ID:")
        if len(parts) == 2:
            fujiedian = parts[0].strip()
            fujiedian_id = parts[1]
        else:
            fujiedian = parts[0].strip()  # 如果没有—ID:，则name即为整个字符串，id_value留空或设置默认值
            fujiedian_id = None

        if self.flag == 0:  # 新增模块
            fu = self.case_db.query_one(
                f"select moduleid,level,parent_path from module where moduleid = '{fujiedian_id}'")  # 获取父节点信息
            level = 0 if fu is None else fu[1] + 1
            parent_id = 0 if fu is None else fu[0]
            addvalue = (parent_id, level, name, 10, remark)
            try:                                # 保存多个数据，统一提交事务
                self.case_db.cursor.execute(
                    'INSERT INTO module (parent_id, level,  modulename, status, remark) VALUES (?,?,?,?,?)',
                    addvalue)
                moduleid = self.case_db.cursor.lastrowid
                parent_path = (fu[2] + '/' + f'{moduleid}' if fu is not None else f'{moduleid}',)  # 更新模块路径
                update_modulesql = f"update module set parent_path = ? where moduleid={moduleid}"
                self.case_db.cursor.execute(update_modulesql, parent_path)
                self.close()                    # 关闭保存窗口
            except Exception as e:
                self.case_db.conn.rollback()    # 发生错误时回滚事务
                self.ts.xinxi(f"保存失败，请检查{e}")
                self.baocun.setEnabled(True)    # 保存按钮恢复
            else:
                self.case_db.conn.commit()      # 在所有数据成功后提交事务

        else:       # 编辑
            if fujiedian == self.parent_name:   # 只修改模块名称
                update_modulesql = f"update module set modulename = ? , remark = ? where moduleid={self.moduleid}"
                if self.case_db.operate_one(update_modulesql, (name,remark)):
                    self.close()                # 关闭保存窗口
                else:
                    self.ts.xinxi("保存失败，请检查")
                    self.baocun.setEnabled(True)  # 保存按钮

            else:   # 修改模块层级
                path = '%' + f'{self.moduleid}' + '/%'  # 查询出子节点
                zi = self.case_db.query_many(
                    f"select moduleid,level,parent_path from module where parent_path like '{path}'")
                if not zi:  # 深度判断
                    shendu = 1
                else:
                    # 检查是否存在第二个值为 '1、2' 的元素
                    contains_one_and_two = any(item[1] == 1 for item in zi) and any(item[1] == 2 for item in zi)
                    shendu = 3 if contains_one_and_two else 2
                if shendu == 3:
                    self.ts.xinxi("模块已有3级，不能修改父节点！")
                    self.baocun.setEnabled(True)  # 保存按钮
                    return

                fu = self.case_db.query_one(
                    f"select moduleid,level,parent_path from module where moduleid = '{fujiedian_id}'")  # 父节点层级

                if fujiedian == "根节点":  # 编辑为根节点
                    update_value = (0, 0, self.moduleid, name, remark)
                    update_modulesql = f'''update module set parent_id = ? ,level=? ,parent_path = ?,modulename = ?,
                     remark = ? where moduleid={self.moduleid}'''
                    try:
                        self.case_db.cursor.execute(update_modulesql, update_value)
                        for z in zi:
                            update_zi = (f'{self.moduleid}', 1, f'{self.moduleid}' + '/' + f'{z[0]}')
                            update_zisql = f'''update module set parent_id = ? ,level=? ,parent_path = ? 
                            where moduleid = {z[0]}'''
                            self.case_db.cursor.execute(update_zisql, update_zi)  # 更新子节点
                        self.close()  # 关闭保存窗口
                    except Exception as e:
                        self.case_db.conn.rollback()  # 发生错误时回滚事务
                        self.ts.xinxi(f"保存失败，请检查{e}")
                        self.baocun.setEnabled(True)  # 保存按钮恢复
                    else:
                        self.case_db.conn.commit()  # 在所有数据成功后提交事务

                elif shendu == 2 and fu[1] == '1':
                    self.ts.xinxi("模块超过3级，请修改父节点！")
                    self.baocun.setEnabled(True)  # 保存按钮
                else:       # 编辑为子节点
                    level = fu[1] + 1
                    parent_path = fu[2] + '/' + f'{self.moduleid}'
                    update_value = (fu[0], level, parent_path, name, remark)
                    update_modulesql = f'''update module set parent_id = ? ,level=? ,parent_path = ?,modulename = ?,
                     remark = ? where moduleid={self.moduleid}'''
                    try:
                        self.case_db.cursor.execute(update_modulesql, update_value)
                        for z in zi:
                            update_zi = (f'{self.moduleid}', level + 1, f'{parent_path}' + '/' + f'{z[0]}')
                            update_zisql = f'''update module set parent_id = ? ,level=? ,parent_path = ? 
                                                where moduleid={z[0]}'''
                            self.case_db.cursor.execute(update_zisql, update_zi)  # 更新子节点
                        self.close()  # 关闭保存窗口
                    except Exception as e:
                        self.case_db.conn.rollback()  # 发生错误时回滚事务
                        self.ts.xinxi(f"保存失败，请检查{e}")
                        self.baocun.setEnabled(True)  # 保存按钮恢复
                    else:
                        self.case_db.conn.commit()  # 在所有数据成功后提交事务
        logging.info('模块保存')

    def yanchong(self):
        """模块名称，提示重复"""
        if self.name.text():
            value = ['%' + self.name.text() + '%']
            row = self.case_db.query_many(
                f'''select modulename,moduleid from module where modulename like ? and moduleid != {self.moduleid} 
                    and status=10''', value)
            output = ''
            if row:
                for item in row:
                    output += f"名称：{item[0]} ID：{item[1]}    "
                self.name.setToolTip(f"有相似模块！{output}")
            else:
                self.name.setToolTip("")

    def closeEvent(self, QCloseEvent):
        """窗口关闭时关闭数据库"""
        self.case_db.over()  # 关闭游标
        # self.case_db.conn.close()
        self.confirmed_signal_tree.emit()  # 发射保存信号
        logging.info("[模块页面,游标关闭]")
